import 'package:flutter/cupertino.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';

class LocationService extends GetxService {
  static LocationService get instance => Get.find<LocationService>();

  ValueNotifier<bool> locationEnabled = ValueNotifier(true);

  Future<double> get longitude async {
    try {
      Position position = await _determinePosition();
      return position.longitude;
    } catch (_) {
      return 0.0;
    }
  }

  Future<double> get latitude async {
    try {
      Position position = await _determinePosition();
      return position.latitude;
    } catch (_) {
      return 0.0;
    }
  }

  Future<Position> _determinePosition() async {
    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();

    if (!serviceEnabled) {
      locationEnabled.value = false;
      return Future.error('定位服务不可用');
    }

    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
    }

    if (permission == LocationPermission.always || permission == LocationPermission.whileInUse) {
      locationEnabled.value = true;
    } else {
      locationEnabled.value = false;
    }

    Position position = await Geolocator.getCurrentPosition();

    return position;
  }

  Future openLocationSetting() async {
    await Geolocator.openLocationSettings();
  }

  Future<String> address() async {
    if (instance.locationEnabled.value) {
      List<Placemark> placeMarks = await placemarkFromCoordinates(await instance.latitude, await instance.longitude);
      if (placeMarks.isNotEmpty) {
        Placemark placeMark = placeMarks[0];
        return placeMark.locality ?? '';
      } else {
        return '';
      }
    } else {
      return '';
    }
  }
}
